<?php

namespace admin\controllers;

use Yii;
use common\helpers\Pager;
use common\helpers\Uploader;
use common\models\Article;

class ArticleController extends Controller {

    // 设置所属一级导航 不设置表示 就是当前类名
    public $parent = 'information';

    /**
     * @name showing Article list
     * @return string
     */
    public function actionArticleList()
    {
        if( ! $this->isJson) {
            return $this->render('article-list');
        }
        $param = $this->request->post();
        $param['category_id'] = max($param['category_id']);
        $param['deleted_at'] = '0';
        $query = Article::filterConditions(Article::initCondition([['title', 'like'], 'category_id', 'deleted_at'], $param));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->orderBy('id desc')->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * @name show article information
     * @param id int by get request
     * @return string
     */
    public function actionArticleDetail()
    {
        $article = null;
        $articleId = $this->request->get('id');
        if($articleId && ( ! $article = Article::canEdit($articleId))) {
            return $this->error('无效的文章（Invalid Article）', 'article/article-list');
        }
        return $this->render('article-detail', ['data' => $article]);
    }
    /**
     * @name insert Article
     * @method post
     * @return string html
     */
    public function actionArticleInsert()
    {
        $param = $this->request->post();
        $param['category_id'] = max($param['category_id']);
        $param['types'] = array_sum($param['types']);
        $article = new Article();
        $article->setAttributesByKey($param);
        if ( ! $article->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($article->errors(), 'article/article-detail');
        }
        if ($article->save()) {
            // 保存成功
            return $this->success('文章（'.$article->title.'）添加成功（Insert Success）', [
                ['title' => '前往文章列表页', 'url' => 'article/article-list'],
                ['title' => '继续修改文章', 'url' => 'article/article-detail?id='.$article->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('文章（'.$article->title.'）添加失败，请重试（System Fail）', 'article/article-detail');
    }
    /***
     * @name 上传图片操作
     * @param $upload array files
     * @return string file path json
     */
    function actionArticleUploader()
    {
        $params = require Yii::getAlias('@common/config/uploader.php');
        // 上传操作
        $uploader = (new Uploader($params['article']))->upload('upload');
        // $this->setStatus($uploader['code'], $uploader['message']);
        return $this->json($uploader);
    }
    /**
     * @name update article information
     * @describe use get(id) to find Article
     * @return string html
     */
    public function actionArticleUpdate()
    {
        /* @var $article Article */
        // id 为必填项，判断管理员存在状态
        $article = Article::canEdit($this->request->get('id'));
        // 未得到，渲染错误页面
        if( ! $article) {
            return $this->error('无效的文章（Invalid Article）', 'article/article-list');
        }
        $oldImage = $article->image;
        $param = $this->request->post();
        $param['category_id'] = max($param['category_id']);
        $param['types'] = array_sum($param['types']);
        $article->setAttributesByKey($param);
        if ( ! $article->validate()) {
            // 删除原图片
            $article->unlinkImage($oldImage);
            // 参数异常，渲染错误页面
            return $this->error($article->errors(), 'article/article-detail?id='.$article->id);
        }
        if ($article->save()) {
            // 保存成功
            return $this->success('文章（'.$article->title.'）更新成功（Update Success）', [
                ['title' => '前往文章列表页', 'url' => 'article/article-list'],
                ['title' => '继续修改文章', 'url' => 'article/article-detail?id='.$article->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('文章（'.$article->title.'）更新失败，请重试（System Error）', 'article/article-detail?id='.$article->id);
    }
    /**
     * @name delete Article
     * @param ids array post request
     * @return string json
     */
    public function actionArticleDelete()
    {
        if( ! (($ids = $this->request->post('id')) || ($ids = $this->request->post('ids')))) {
            return $this->json('Invalid.Param', '请求异常（Invalid Param）');
        }
        else if(Article::trashAll(['id' => $ids])) {
            return $this->json(SuccessCode, '文章删除成功（Delete Success）');
        }
        return $this->json('System.Error', '文章删除失败（System Error）');
    }
}